package com.qitianyong.selfclass;

import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;

import com.qitianyong.sgkusbcamera.R;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.LinkedList;

import static com.qitianyong.selfclass.PublicMethod.getCurrentTime;

/**
 * Created by gy on 2017/6/6.
 */

public class LogUtils {
    public final static int ADD_LOG = 0;
    public final static int SAVE_LOG = 1;
    private static LinkedList<String> operateLogs = new LinkedList<>();
    public static Handler handler;
    public static HashMap<Integer, String> ids = new HashMap<>();
    public static long lastSaveLogTims = 0;

    public static void addLog(String log) {
        Message obtain = Message.obtain();
        obtain.obj = log;
        obtain.what = ADD_LOG;
        handler.sendMessage(obtain);
    }

    public static void addClickLog(int id) {
        Message obtain = Message.obtain();
        String name = ids.get(id);
        obtain.obj = (name != null ? name : id + " ") + "click";
        obtain.what = ADD_LOG;
        handler.sendMessage(obtain);
    }

    public static String[] getAllLogs() {
        String[] strs;
        synchronized (LogUtils.class) {
            strs = new String[operateLogs.size()];
            int index = 0;
            for (String operateLog : operateLogs) {
                strs[index++] = operateLog;
            }
        }
        return strs;
    }

    private static Thread logThread = new Thread(new Runnable() {

        @Override
        public void run() {

            Looper.prepare();
            createHandle();
            Class<R.id> idClass = R.id.class;
            Field[] fields = idClass.getFields();
            try {
                for (Field field : fields) {
                    int anInt = field.getInt(idClass);
                    String name = field.getName();
                    ids.put(anInt, name);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            Looper.loop();
        }

        void createHandle() {
            handler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    String absolutePath;
                    if ((Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
                            || !Environment.isExternalStorageRemovable()) &&  CustomApp.customApp.getExternalCacheDir() != null) {
                        absolutePath = CustomApp.customApp.getExternalCacheDir().getPath();
                    } else {
                        absolutePath =  CustomApp.customApp.getCacheDir().getPath();
                    }

                    switch (msg.what) {
                        case ADD_LOG:
                            synchronized (LogUtils.class) {
                                if (operateLogs.size() == 0) {
                                    BufferedReader reader = null;
                                    try {
                                        File file = new File(absolutePath + "/log.txt");
                                        File path = new File(absolutePath);
                                        if (!path.exists()) {
                                            path.mkdirs();
                                        }
                                        if (!file.exists()) {
                                            file.createNewFile();
                                        }
                                        reader = new BufferedReader(new FileReader(file));
                                        while (true) {
                                            String s = reader.readLine();
                                            if (TextUtils.isEmpty(s)) {
                                                break;
                                            } else {
                                                operateLogs.addLast(s);
                                            }
                                        }
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    } finally {
                                        if (reader != null) {
                                            try {
                                                reader.close();
                                            } catch (IOException e) {
                                                e.printStackTrace();
                                            }
                                        }
                                    }
                                }
                                if (operateLogs.size() > 1000) {
                                    operateLogs.removeLast();
                                }
                                operateLogs.addFirst(getCurrentTime() + " " + msg.obj.toString());
                            }
                            break;
                        case SAVE_LOG:
                            long l = System.currentTimeMillis();
                            if (l - lastSaveLogTims < 60000) {
                                return;
                            }
                            lastSaveLogTims = l;
                            synchronized (LogUtils.class) {
                                if (operateLogs.size() != 0) {
                                    BufferedWriter writer = null;
                                    try {
                                        writer = new BufferedWriter(new FileWriter(absolutePath + "/log.txt"));
                                        for (String str :
                                                operateLogs) {
                                            writer.write(str);
                                            writer.newLine();
                                        }
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    } finally {
                                        if (writer != null) {
                                            try {
                                                writer.close();
                                            } catch (IOException e) {
                                                e.printStackTrace();
                                            }
                                        }
                                    }
                                }
                            }
                            break;
                    }
                }
            };
        }
    });

    static {
        logThread.start();
    }
}
